package com.elite.groovy.callback

import com.elite.groovy.davco.clink.ClinkUtils
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

/**
 * @projectName: Groovy
 * @package: com.elite.groovy.callback
 * @className: apiClinkAgentDurationLog
 * @description: 同步天润坐席状态数据
 * @author: LiJT
 * @date: 2023-10-27 11:13
 * @version: 1.0
 */

public class apiClinkAgentDurationLog implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiClinkAgentDurationLog.class);

    private static boolean isRun = true;

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        try {

            // 封装调用头Heads
            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/json");

            String StartTime = request.getParameter("StartTime");
            String EndTime = request.getParameter("EndTime");
            log.debug("doCallBack API StartTime:" + StartTime + " EndTime:" + EndTime);

            long currentTimeMillis = (long) (System.currentTimeMillis() / 1000);
            String StartTimeDefault = String.valueOf((currentTimeMillis - 172800));
            String EndTimeDefault = String.valueOf(currentTimeMillis);

            StartTime = KHUtil.isNull(StartTime) ? StartTimeDefault : StartTime;
            EndTime = KHUtil.isNull(EndTime) ? EndTimeDefault : EndTime;
            log.debug("同步天润坐席状态数据 StartTime:" + StartTime + "(" + stampToDate(StartTime) + ")" + " EndTime:" + EndTime + "(" + stampToDate(EndTime) + ")");

            int Offset = 0;
            isRun = true;
            while (isRun && Offset < 1000) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                toDoGet(eliteBean, Long.parseLong(StartTime), Long.parseLong(EndTime), Offset * 100, headMap);
                Offset = Offset + 1;
            }

            log.debug("同步天润坐席状态数据 结束执行...");
        } catch (Exception e) {
            log.error("同步天润坐席状态数据，接口处理异常：" + e.getMessage());
            return e.getMessage();

        }

        return "SUCC";

    }

    static toDoGet(EliteBean eliteBean, Long StartTime, Long EndTime, int Offset, Map<String, String> headMap) {

        //处理主数据
        log.debug("同步天润坐席状态数据 toDoGet Data StartTime:" + StartTime + " EndTime:" + EndTime + " Offset:" + Offset);

        // 系统接入-GET
        String getPath = "/cc/list_log_agent_duration?";

        Map<String, String> queryParams = new HashMap<String, String>();
        queryParams.put("startTime", String.valueOf(StartTime));
        queryParams.put("endTime", String.valueOf(EndTime));
        queryParams.put("offset", String.valueOf(Offset));
        queryParams.put("limit", "100");
        String doGETRes = ClinkUtils.doClinkCall("GET", getPath, queryParams, headMap, null);
        // log.debug("系统接入 doGETRes:" + doGETRes);

        JSONObject doGETJSON = JSONObject.fromObject(doGETRes);
        // log.debug("天润监控返回坐席信息:" + doGETJSON);

        JSONArray dataArray = doGETJSON.getJSONArray("agentDurationLogs");
        int dataArrayLen = dataArray.size();

        log.info("同步天润坐席状态数据 Data Result size:" + dataArrayLen);
        if (dataArrayLen <= 0) {
            isRun = false;
        }

        JSONObject dataObject = null;
        String sql = null;
        List sqlResult = null;
        int Countnum = 0;
        for (int i = 0; i < dataArrayLen; i++) {
            dataObject = dataArray.getJSONObject(i);
            String agentName = KHUtil.GetSFJV(dataObject, "agentName");
            String startTime = stampToDate(KHUtil.GetSFJV(dataObject, "startTime") + "000");

            sql = "Select Count(*) As Count From clink_list_log_agent_duration Where Agentname = '" + agentName + "' And Starttime = '" + startTime + "'";
            sqlResult = eliteBean.chaxun_sql(sql, 'dataSource');
            Countnum = sqlResult.get(0).get("Count");

            if (Countnum <= 0) {

                sql = '''Insert Into clink_list_log_agent_duration
                          (Cno, Agentname, Qname, Starttime, Endtime, Duration, Statedesc, Createtime, Data1, Data2, Detail, Statistictype)
                        Values
                          (\'''' + KHUtil.GetSFJV(dataObject, "cno") + '''\', \'''' + agentName + '''\', \'''' + KHUtil.GetSFJV(dataObject, "qname") + '''\', \'''' + startTime + '''\', \'''' + stampToDate(KHUtil.GetSFJV(dataObject, "endTime") + "000") + '''\', \'''' + KHUtil.GetSFJV(dataObject, "duration") + '''\', \'''' + KHUtil.GetSFJV(dataObject, "stateDesc") + '''\', \'''' + KHUtil.GetSFJV(dataObject, "createTime") + '''\', \'''' + KHUtil.GetSFJV(dataObject, "data1") + '''\', \'''' + KHUtil.GetSFJV(dataObject, "data2") + '''\', \'''' + KHUtil.GetSFJV(dataObject, "detail") + '''\', \'''' + KHUtil.GetSFJV(dataObject, "statisticType") + '''\')
                        ''';

                eliteBean.update(sql, 'dataSource');

            }
        }

    }

    static String stampToDate(String s) {
        String res = s.length() > 10 ? s : s + "000";

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        long lt = new Long(res);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

}